package com.csi.service.impl;

import com.csi.domain.UserBook;
import com.csi.mapper.UserBookMapper;
import com.csi.service.UserBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.print.Book;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

@Service
public class UserBookServiceImpl implements UserBookService {

    @Autowired
    private UserBookMapper userBookMapper;

    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
    private ConcurrentHashMap<UserBook, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<>();

    /**
     * 用户所有订单
     * @return
     */
    @Override
    public Map<String, Object> showUserBook(long hotelId) {
        return userBookMapper.showUserBook(hotelId);
    }

    /**
     * 根据入住日、离店日、房型模糊查询可订几间房
     * @param roomId
     * @param check_time
     * @param leave_time
     * @return
     */
    @Override
    public int findRoomNum(int roomId, String check_time, String leave_time) {
        return userBookMapper.findRoomNum(roomId, check_time, leave_time);
    }

    /**
     * 根据房型Id查询预定页面酒店及房型信息
     * @param roomTypeId
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> findByRoomTypeId4Info(int roomTypeId) {

        Map<String, Object> map = userBookMapper.findByRoomTypeId4Info(roomTypeId);

        List<String> list = userBookMapper.findByRoomTypeId4facility(roomTypeId);

        map.put("list", list);

        return map;
    }

    /**
     * 添加订单(用户可选多个房间)
     * @param userId
     * @param checkTime
     * @param leaveTime
     * @param roomNum
     * @param price
     * @param phone
     * @param hotelId
     * @param roomTypeId
     * @return
     */
    @Override
    @Transactional
    public int saveBook(long userId,String checkTime,String leaveTime,int roomNum,double price,String phone,long hotelId,long roomTypeId) throws ParseException {

        List<Long> rooms = userBookMapper.findRoomId(roomTypeId,checkTime,leaveTime);

        List<UserBook> books = new ArrayList<>();

        for(int i=0;i<roomNum;i++){
            UserBook userBook = new UserBook();
            userBook.setRoomId(rooms.get(i));
            userBook.setPhone(phone);
            userBook.setHotelId(hotelId);
            userBook.setPayStatus("待支付");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(checkTime);
            Timestamp check = new Timestamp(date.getTime());

            Date date1 = sdf.parse(leaveTime);
            Timestamp leave = new Timestamp(date1.getTime());

            userBook.setCheckTime(check);
            userBook.setLeaveTime(leave);
            userBook.setBookPrice(BigDecimal.valueOf(price));
            userBook.setUserId(userId);
            books.add(userBook);
        }

        int result = userBookMapper.saveBook(books);

        scheduleUnlockTask(userId,checkTime,leaveTime,price,phone,hotelId);


        return result;
    }


    private void scheduleUnlockTask(long userId,String checkTime,String leaveTime,double price,String phone,long hotelId){
        long delay = 30*60*1000;

        UserBook userBook = new UserBook();

        ScheduledFuture<?> future = scheduledExecutorService.schedule(() ->{
            userBook.setUserId(userId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = sdf.parse(checkTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Timestamp check = new Timestamp(date.getTime());

            Date date1 = null;
            try {
                date1 = sdf.parse(leaveTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Timestamp leave = new Timestamp(date1.getTime());

            userBook.setCheckTime(check);
            userBook.setLeaveTime(leave);
            userBook.setPhone(phone);
            userBook.setBookPrice(BigDecimal.valueOf(price));
            userBook.setHotelId(hotelId);

            userBookMapper.cancel(userBook);

        },delay, TimeUnit.MILLISECONDS);

        scheduledFutures.put(userBook, future);
    }

    /**
     * 用户支付
     * @param userBook
     * @return
     */
    @Override
    public int payment(UserBook userBook) {

        int result = userBookMapper.payment(userBook);

        ScheduledFuture<?> future = scheduledFutures.get(userBook);
        if(future!=null){
            future.cancel(true);
            scheduledFutures.remove(userBook);
        }
        return result;
    }

    /**
     * 已完成
     * @param bookId
     * @return
     */
    @Override
    public int completed(long bookId) {
        return userBookMapper.completed(bookId);
    }

    /**
     * 待评价
     * @param bookId
     * @return
     */
    @Override
    public int evaluated(long bookId) {
        return userBookMapper.evaluated(bookId);
    }


}
